/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.memberView;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

import com.dianlian.pss.inter.Connection;
import com.dianlian.pss.inter.ws.UserMgr;
import com.ruipengkj.ApplicationContext;
import com.ruipengkj.CardComponentListener;
import com.ruipengkj.bean.TSendCardRecord;
import com.ruipengkj.bean.TUser;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.DateUtil;
import com.ruipengkj.commons.util.MatcherFormatUtil;
import com.ruipengkj.commons.util.SwingUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.service.TUserService;
import com.ruipengkj.view.base.BasePanel;
/**
 * 说明：
 * 发 卡UI
 * @Author：黄盛强
 * @Date：2012-03-20
 */
public class MemberCreateCardPanel extends BasePanel {
	
	private static final long serialVersionUID = 1L;
	//private JLabelJTextFieldComponent number = null;//会员编号
	private JLabelJTextFieldComponent cardNumTF = null;///会员卡号
	private JLabelJTextFieldComponent nameTF = null; //姓名
	private JLabelJTextFieldComponent mobileTF = null; //手机号码
	private JLabelJTextFieldComponent initMoneyTF = null;//初始金额
	
	private JButton sureButton = null; //确定
	private JButton cancelButton = null; //取消
	private JLabel label= null;
	private TUserService tUserService;
	public MemberCreateCardPanel() {
		tUserService=BuildSpringApplication.getInstance().getTUserServiceImpl();
		this.addComponents();
		this.initListener();
		cardNumTF.getText().addComponentListener(new CardComponentListener());
	}
	
	private void addComponents() {
		JPanel main_jp=uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		main_jp.setBorder(BorderFactory.createTitledBorder("会员发卡"));
		
		JPanel cardNum_jp=uiFactory.createFlowJPanel(FlowLayout.LEFT);
		cardNumTF = new JLabelJTextFieldComponent("  *", "卡    号：",30);
		cardNumTF.getText().setEditable(false);
		cardNumTF.getText().setText(DateUtil.formatD(new Date(), "MMddHHmmss"));
		cardNum_jp.add(cardNumTF);
//		number = new JLabelJTextFieldComponent("   *", "会员编号：",30);
//		number.getText().setText(UUID.GenUUID15());
//		number.getText().setEditable(false);
		nameTF = new JLabelJTextFieldComponent("   *", "会员名称：", 30);
		mobileTF= new JLabelJTextFieldComponent("   *", "手机号码：", 30);
		initMoneyTF = new JLabelJTextFieldComponent("   *", "初始金额：", 30);
		initMoneyTF.getText().setText("0.00");
		
		JPanel jp6 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		sureButton = new RPJButtonBlue("确定(Ctrl+Y)");
		cancelButton = new RPJButtonGray("清空");
		JPanel main_jp1=new JPanel();
		label = new JLabel();
		ImageIcon s=SwingUtil.getOpenSwingImage("jiazai.png");
		//System.out.println(s.getDescription()+"*****************************************************************************");
		label.setIcon(s);
//		SmallPic=new JPanelComponent(ImageIO.read(new File(""), 100, 100);
		main_jp1.add(label);
		main_jp1.add(nameTF);
		jp6.add(sureButton);
		jp6.add(cancelButton);
//		main_jp.add(number);
		main_jp.add(cardNum_jp);
		main_jp.add(nameTF);
		main_jp.add(mobileTF);
		main_jp.add(initMoneyTF);
		main_jp.add(jp6);
		label.setVisible(false);
		main_jp.add(label);
		this.add(main_jp);
	}
	
	private void initListener(){
		sureButton.addActionListener(this);
		sureButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Y, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		cancelButton.addActionListener(this);
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource()==sureButton){
			//提交
			String name=nameTF.getText().getText().trim();//会员姓名
			String cardNum=cardNumTF.getText().getText().trim();//卡号
			String mobile=mobileTF.getText().getText().trim(); //手机号码
			String initMoney=initMoneyTF.getText().getText().trim();//初始金额

			if(cardNum.equals("")||cardNum.length()>15){
				JOptionPane.showMessageDialog(null, "卡号不能为空，且不能大于15个字");
				cardNumTF.getText().requestFocus();
				return;
			}
			
			if(name.equals("")||name.length()>20){
				JOptionPane.showMessageDialog(null, "会员名称不能为空，且不能大于20个字");
				nameTF.getText().requestFocus();
				return;
			}
			if(mobile.equals("")||!MatcherFormatUtil.checkMobileScheme(mobile)){
				JOptionPane.showMessageDialog(null, "手机号码不能为空，请输入正确的手机号码");
				mobileTF.getText().requestFocus();
				return;
			}
			if(initMoney.equals("")||!MatcherFormatUtil.MatcherPriceScheme(initMoney)){
				JOptionPane.showMessageDialog(null, "初始金额不能为空，请确认格式是否正确");
				initMoneyTF.getText().requestFocus();
				return;
			}
			Date date=new Date();
			TSendCardRecord tSendCardRecord=new TSendCardRecord();
			tSendCardRecord.setSendCardRecordID(UUID.GenUUID15());
			tSendCardRecord.setCardNum(cardNum);
			tSendCardRecord.setSendCardTime(date);
			final TUser tUser=new TUser();
			tUser.setUserID(UUID.GenUUID15());
			tUser.setRealName(name);
			tUser.setMobile(mobile);
			tUser.setMoney(Double.parseDouble(initMoney));
			tUser.setCreateTime(date);
			tUser.setLastLoginTime(date);
			tUser.setSendCardTime(date);
			tUser.setCardNum(cardNum);
			tUser.getTSendCardRecords().add(tSendCardRecord);
			boolean siteLoad = false;
			try {
				label.setVisible(true);	
				if(tUserService.getByMobileService(mobile)!=null){
					JOptionPane.showMessageDialog(null, "该手机号码已经存在，请重新输入");
					mobileTF.getText().requestFocus();
					return;
				}
				if(tUserService.getByCardNumService(cardNumTF.getText().getText().trim())!=null){
					JOptionPane.showMessageDialog(null, "该卡号已经存在，请重新输入");
					cardNumTF.getText().requestFocus();
					return;
				}
				//网站验证
				final MemberCreateCardPanel this_ = this;
				siteLoad = true;
				new Thread(new Runnable(){
					
					public void run()
					{
						try
						{
                            if(!ApplicationContext.CardUtilThread.isSearchedCard())
                            {
                                throw new Exception("在发卡过程中请不要移开或者更换卡");
                            }
                            String currCardNum = tUser.getCardNum();
							Connection conn = ApplicationContext.getSynConnection();
					        UserMgr um =conn.getSiteUserMgr();
					        //手机号，用户名，卡号
					        String userID;
					        userID = um.sendCard(tUser.getMobile(), tUser.getRealName(), tUser.getCardNum());
                            int response=0;
                            while((response == 0 && !ApplicationContext.CardUtilThread.isSearchedCard())
                                    || !cardNumTF.getText().getText().trim().equals(currCardNum))
                            {
                                Object[] options = {"确定","取消"};
                                response=JOptionPane.showOptionDialog(MemberCreateCardPanel.this,
                                        "卡号为"+currCardNum+"的卡已被系统记录为发出，但无法写入，请确保在发卡过程中不要移开卡或更新其它卡", "警告",JOptionPane.YES_OPTION,
                                JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                                if(response != 0)
                                {
                                    throw new Exception("卡号为"+currCardNum+"的卡已被系统记录为发出，但无法写入");
                                }
                            }
                            ApplicationContext.CardUtilThread.sendCard(tUser.getUserID(), tUser.getMobile(), tUser.getRealName());
                            tUserService.saveService(tUser);
							BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("会员发卡，卡号为：+"+cardNumTF.getText().getText().trim());
							//JOptionPane.showMessageDialog(null, "操作成功");
							//this.clear();
							//tUserService.saveService(tUser);
							//BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("会员发卡，卡号为：+"+cardNumTF.getText().getText().trim());
							SwingUtilities.invokeAndWait(new Runnable(){
								public void run()
								{
									JOptionPane.showMessageDialog(null, "操作成功");
									this_.clear();
								}
							});		
						}
						catch(Exception e)
						{
							e.printStackTrace();
							JOptionPane.showMessageDialog(null, "操作失败:" + e.getMessage());
						}finally{
							label.setVisible(false);
						} 
					}
				}).start();
				
			} catch (Exception e1) {
				e1.printStackTrace();
				JOptionPane.showMessageDialog(null, "操作失败，请重新操作");
				this.clear();
			}finally{
				if(!siteLoad)label.setVisible(false);
			}
		} else if (e.getSource() == cancelButton) {
			clear();
		}
	}

	@Override
	public void clear() {
		cardNumTF.getText().setText("");//会员卡号
		nameTF.getText().setText(""); //会员姓名
		mobileTF.getText().setText("") ; //手机号码
		initMoneyTF .getText().setText("");//初始金额
		cardNumTF.getText().requestFocus();
		
		//cardNumTF.getText().setText(DateUtil.formatD(new Date(), "MMddHHmmss"));
		ApplicationContext.listenCard(cardNumTF.getText(), ApplicationContext.CardType.CT_DLInited);
	}
}
